package com.chaos.framework.starter.config.thread;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Jacky
 **/
@EnableAsync
@Configuration
public class AsyncConfig {

    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutorWrapper executor = new ThreadPoolTaskExecutorWrapper();
        executor.setCorePoolSize(16);
        executor.setMaxPoolSize(32);
        executor.setQueueCapacity(200);

        executor.setKeepAliveSeconds(60);
        executor.setAwaitTerminationSeconds(60);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }

    /**
     * io密集型的线程池
     *
     * @return
     */
    @ConditionalOnMissingBean
    @Bean(name = "ioIntensiveThreadPool")
    public Executor ioIntensiveThreadPool() {
        return ThreadPoolFactory.instance(ThreadPoolTypeEnum.IO_INTENSIVE);
    }

    /**
     * cpu密集型的线程池
     *
     * @return
     */
    @ConditionalOnMissingBean
    @Bean(name = "cpuIntensiveThreadPool")
    public Executor cpuIntensiveThreadPool() {
        return ThreadPoolFactory.instance(ThreadPoolTypeEnum.CPU_INTENSIVE);
    }

}

